import { Product, Page, ResultBean, Device } from '@shared/bean';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema, SFComponent, SFSchemaEnum } from '@delon/form';

@Component({
  selector: 'app-devices-list-edit',
  templateUrl: './edit.component.html',
})
export class DevicesListEditComponent implements OnInit {
  products: Product[] = [];
  record: any = {};
  i: Device;
  @ViewChild('sf') sf: SFComponent;
  schema: SFSchema = {
    type: 'object',
    properties: {
      name: { type: 'string', title: '编号' },
      username: { type: 'string', title: '用户名' },
      product: { type: 'string', title: '产品', enum: []},
      image: { type: 'string', title: '头像'},
      description: { type: 'string', title: '描述'}
    },
    required: ['name', 'product'],
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 60,
      grid: { span: 10 },
    },
    $name: {
      widget: 'string'
    },
    $username: {
      widget: 'string'
    },
    $product: {
      widget: 'select'
    },
    $image: {
      widget: 'upload',
      action: '/upload',
      resReName: 'url'
    },
    $description: {
      widget: 'textarea',
      autosize: {minRows: 2},
      grid: { span: 24 },
    },
  };

  constructor(
    private modal: NzModalRef,
    public msgSrv: NzMessageService,
    public http: _HttpClient,
  ) {}

  ngOnInit(): void {
    if (this.record.id > 0) {
      this.http.get(`/api/devices/${this.record.id}`).subscribe((res: ResultBean<Device>) => {
        this.i = res.data;
      });
    }
    this.http.post('/api/products/query').subscribe((res: ResultBean<Page>) => {
      const enums: SFSchemaEnum[] = [];
      res.data.content.map((product: Product) => {
        enums.push({label: product.name, value: product});
        if (this.record.id > 0 && this.record.product.id === product.id) {
          this.schema.properties.product.default = product;
        }
      });
      this.schema.properties.product.enum = enums;
      this.sf.refreshSchema();
    });
  }

  save(value: any) {
    if (value.id > 0) {
      this.http.put(`/api/devices`, value).subscribe(res => {
        this.msgSrv.success('保存成功');
        this.modal.close(true);
      });
    } else {
      this.http.post(`/api/devices`, value).subscribe(res => {
        this.msgSrv.success('保存成功');
        this.modal.close(true);
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
